# -*- coding: utf-8 -*-
#encoding=utf-8

# 导包
import pandas as pd
import os
from pyecharts import options as opts
from pyecharts.globals import ThemeType
from pyecharts.charts import Bar
from pyecharts.charts import Pie

## 清洗数据
def clear_data():
    ##写入到excel
    import openpyxl
    outwb = openpyxl.Workbook()  # 打开一个将写的文件
    outws = outwb.create_sheet(index=0)  # 在将写的文件创建sheet

    outws.cell(row=1, column=1, value="index")
    outws.cell(row=1, column=2, value="商品名称")
    outws.cell(row=1, column=3, value="打折")
    outws.cell(row=1, column=4, value="原价")
    outws.cell(row=1, column=5, value="秒杀价")
    outws.cell(row=1, column=6, value="评论数")
    outws.cell(row=1, column=7, value="好评数")
    outws.cell(row=1, column=8, value="中评数")
    outws.cell(row=1, column=9, value="差评数")
    outws.cell(row=1, column=10, value="好评率")
    count = 2


    #读入数据
    df_all = pd.read_csv("618畅销京东商品-李运辰.csv",engine="python")
    df = df_all.copy()

    data2 = df['商品名称'].tolist()
    data3 = df['打折'].tolist()
    data4 = df['原价'].tolist()
    data5 = df['秒杀价'].tolist()
    data6 = df['评论数'].tolist()

    data7 = df['好评数'].tolist()
    data8 = df['中评数'].tolist()
    data9 = df['差评数'].tolist()
    data10 = df['好评率'].tolist()


    #标题过长，不方便后面的画图
    for d2 in range(len(data2)):
        tem = data2[d2]
        tem = tem.replace("京东京造", "").replace("xPLUS会员店", "").replace("PLUS会员店", "").replace("×PLUS会员", "").replace("PLUS会员", "").replace("【新茶上市】","")
        tem_list = tem.split(" ")
        d22 = ""
        for t in tem_list:
            d22 = d22 +t
            if len(d22)>3:
                if len(d22)>10:
                    d22 = d22[0:10]
                data2[d2] = d22
                break
    #打折字段中含有折字，在进行排序时不能直接转数值型。
    for d3 in range(len(data3)):
        tem = data3[d3]
        data3[d3] = tem.replace("折","")
    #好评数中的万，转为具体数值，如1.2万转为12000
    for d7 in range(len(data7)):
        tem = data7[d7]
        if "万" in tem:
            tem = tem.replace("万","")
            data7[d7] = str(int(float(tem)*10000))


    for i in range(len(data2)):
        outws.cell(row=count, column=1, value=str(count-1))
        outws.cell(row=count, column=2, value=data2[i])
        outws.cell(row=count, column=3, value=data3[i])
        outws.cell(row=count, column=4, value=data4[i])
        outws.cell(row=count, column=5, value=data5[i])
        outws.cell(row=count, column=6, value=data6[i])
        outws.cell(row=count, column=7, value=data7[i])
        outws.cell(row=count, column=8, value=data8[i])
        outws.cell(row=count, column=9, value=data9[i])
        outws.cell(row=count, column=10, value=data10[i])
        count = count+1

    outwb.save("618畅销京东商品-李运辰.xls")  # 保存结果

#读入数据
df_all = pd.read_csv("618畅销京东商品清洗后-李运辰.csv",engine="python")
df = df_all.copy()

#可视化-商品打折力度
def an1():
    p_min = df.groupby('商品名称')['打折'].agg(['min'])['min'].sort_values(ascending=True).reset_index()
    p_min.columns = ['商品名称', '打折']
    name = (p_min['商品名称']).tolist()[0:15]
    dict_values = (p_min['打折']).tolist()[0:15]
    #链式调用
    c = (
        Bar(
            init_opts=opts.InitOpts(  # 初始配置项
                theme=ThemeType.MACARONS,
                animation_opts=opts.AnimationOpts(
                    animation_delay=1000, animation_easing="cubicOut"  # 初始动画延迟和缓动效果
                ))
        )
            .add_xaxis(xaxis_data=name)  # x轴
            .add_yaxis(series_name="打折力度", y_axis=dict_values)  # y轴
            .set_global_opts(
            title_opts=opts.TitleOpts(title='', subtitle='',  # 标题配置和调整位置
                                      title_textstyle_opts=opts.TextStyleOpts(
                                          font_family='SimHei', font_size=25, font_weight='bold', color='red',
                                      ), pos_left="90%", pos_top="2",
                                      ),
            xaxis_opts=opts.AxisOpts(name='商品', axislabel_opts=opts.LabelOpts(rotate=20)),
            # 设置x名称和Label rotate解决标签名字过长使用
            yaxis_opts=opts.AxisOpts(name='打折度'),

        )
            .render("商品打折力度.html")
    )

#可视化-好评率统计
def an2():
    data10 = df['好评率'].tolist()
    #统计并排序
    data10_0=set(data10)
    data10_1=[]
    for i in data10_0:
        data10_1.append([i,data10.count(i)])
    data10_1.sort(key = lambda x:(x[1], x[0]),reverse = True)

    name =[]
    dict_values = []
    for k in data10_1:
        name.append(k[0])
        dict_values.append(k[1])
    #链式调用
    c = (
        Bar(
            init_opts=opts.InitOpts(  # 初始配置项
                theme=ThemeType.MACARONS,
                animation_opts=opts.AnimationOpts(
                    animation_delay=1000, animation_easing="cubicOut"  # 初始动画延迟和缓动效果
                ))
        )
            .add_xaxis(xaxis_data=name)  # x轴
            .add_yaxis(series_name="好评率统计", y_axis=dict_values)  # y轴
            .set_global_opts(
            title_opts=opts.TitleOpts(title='', subtitle='',  # 标题配置和调整位置
                                      title_textstyle_opts=opts.TextStyleOpts(
                                          font_family='SimHei', font_size=25, font_weight='bold', color='red',
                                      ), pos_left="90%", pos_top="10",
                                      ),
            xaxis_opts=opts.AxisOpts(name='好评率', axislabel_opts=opts.LabelOpts(rotate=45)),
            # 设置x名称和Label rotate解决标签名字过长使用
            yaxis_opts=opts.AxisOpts(name='数据量'),

        )
            .render("好评率统计.html")
    )


#可视化-畅销商品销量排行
def an3():
    p_max = df.groupby('商品名称')['评论数'].agg(['max'])['max'].sort_values(ascending=False).reset_index()
    p_max.columns = ['商品名称', '评论数']
    name = (p_max['商品名称']).tolist()[0:15]
    dict_values = (p_max['评论数']).tolist()[0:15]
    #链式调用
    c = (
        Bar(
            init_opts=opts.InitOpts(  # 初始配置项
                theme=ThemeType.MACARONS,
                animation_opts=opts.AnimationOpts(
                    animation_delay=1000, animation_easing="cubicOut"  # 初始动画延迟和缓动效果
                ))
        )
            .add_xaxis(xaxis_data=name)  # x轴
            .add_yaxis(series_name="畅销商品销量排行", y_axis=dict_values)  # y轴
            .set_global_opts(
            title_opts=opts.TitleOpts(title='', subtitle='',  # 标题配置和调整位置
                                      title_textstyle_opts=opts.TextStyleOpts(
                                          font_family='SimHei', font_size=25, font_weight='bold', color='red',
                                      ), pos_left="90%", pos_top="2",
                                      ),
            xaxis_opts=opts.AxisOpts(name='商品', axislabel_opts=opts.LabelOpts(rotate=20)),
            # 设置x名称和Label rotate解决标签名字过长使用
            yaxis_opts=opts.AxisOpts(name='销量'),

        )
            .render("畅销商品销量排行.html")
    )

#可视化-畅销商品前15名原价与秒杀价对比
def an4():
    p_max = df.groupby('商品名称')['评论数'].agg(['max'])['max'].sort_values(ascending=False).reset_index()
    p_max.columns = ['商品名称', '评论数']
    name = (p_max['商品名称']).tolist()[0:15]
    data2 = df['商品名称'].tolist()
    data4 = df['原价'].tolist()
    data5 = df['秒杀价'].tolist()

    dict_values1 = []
    dict_values2 = []
    for k in name:
        dict_values1.append(data4[data2.index(k)])
        dict_values2.append(data5[data2.index(k)])

    bar = (
        Bar(init_opts=opts.InitOpts(theme=ThemeType.DARK))
        .add_xaxis(name)
        .add_yaxis("原价", dict_values1)
        .add_yaxis("秒杀价", dict_values2)
        .set_global_opts(title_opts=opts.TitleOpts(title="畅销商品前15名原价与秒杀价对比",subtitle="单位/元"),
                         xaxis_opts=opts.AxisOpts(name='商品', axislabel_opts=opts.LabelOpts(rotate=20)
        ))
    )
    bar.render("畅销商品前15名原价与秒杀价对比.html")


